package servlet;

import com.alibaba.fastjson.JSON;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    //服务端处理请求的post方法
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置请求响应的字符编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("loginName");
        String password = request.getParameter("loginPwd");

        //2.实例化out对象
        PrintWriter out = response.getWriter();
        //3.给客户端响应信息
        //out.print(true);     //响应boolean类型
        //out.print("登录成功");//响应String类型
//        List<String> list = Arrays.asList("aaa", "bbb", "ccc");
//        out.print(list);//响应 List<String>类型
        User user = new User(1001, "张三丰", '男', new Date());
        //out.print(user.toString());//内存地址

        //将对象序列化为json(1.引用jar包，2.调用序列化方法)
        //fastjson
        //String jsonString = JSON.toJSONString(user);
        // out.print(jsonString);

        Map<String, Object> resultMaps = new HashMap<>();
        if ("admin".equals(username) && "666666".equals(password)) {
            request.getSession().setAttribute("user",user);
            resultMaps.put("code", 200);
            resultMaps.put("msg", "登录成功");
            resultMaps.put("data", user);
        } else {
            resultMaps.put("code", 400);
            resultMaps.put("msg", "登录失败！用户名密或码错误！");
        }


        String outResult = JSON.toJSONString(resultMaps);
        out.print(outResult);

        //4.关闭out对象
        out.flush();
        out.close();
    }


}
